package com.maskota;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class DetalleProductos extends Activity {
	boolean internet;
	InputStream is = null;
	String result;
	SharedPreferences preferences;
	String vartipoproductos;
	String[] id,producto,precio,imagen;
	ImageView improd1,improd2,improd3,improd4;
	TextView txt1,txt2,txt3,txt4,txtp1,txtp2,txtp3,txtp4,productotitulo;
	String url="http://maskota.zedtrix.com/img/productos/";
	public UsuariosSQLiteHelper usdbh;
    public SQLiteDatabase db;
    int ind;
    int  posicion;
    String valor;

	
	public static boolean isInternetConnectionActive(Context context) {
		  NetworkInfo networkInfo = ((ConnectivityManager) context
		    .getSystemService(Context.CONNECTIVITY_SERVICE))
		    .getActiveNetworkInfo();

		  if(networkInfo == null || !networkInfo.isConnected()) {
		   return false;
		  }
		  return true;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detalleproducto);
		
		Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/vagroundedbold.ttf");
		productotitulo = (TextView) findViewById(R.id.productos);
		productotitulo.setTypeface(tf);
		
	    usdbh = new UsuariosSQLiteHelper(this, "Maskota", null, 1);
		
		preferences=getSharedPreferences("MasKotaPreferencias", MODE_PRIVATE);
		vartipoproductos=preferences.getString("vartipoproducto", ""+0);
		
		improd1=(ImageView) findViewById(R.id.imagenproducto1);
		improd2=(ImageView) findViewById(R.id.imagenproducto2);
		improd3=(ImageView) findViewById(R.id.imagenproducto3);
		improd4=(ImageView) findViewById(R.id.imagenproducto4);
		txt1=(TextView) findViewById(R.id.textoproducto1);
		txt2=(TextView) findViewById(R.id.textoproducto2);
		txt3=(TextView) findViewById(R.id.textoproducto3);
		txt4=(TextView) findViewById(R.id.textoproducto4);
		txtp1=(TextView) findViewById(R.id.textoprecio1);
		txtp2=(TextView) findViewById(R.id.textoprecio2);
		txtp3=(TextView) findViewById(R.id.textoprecio3);
		txtp4=(TextView) findViewById(R.id.textoprecio4);


		internet = isInternetConnectionActive(DetalleProductos.this);
		if (internet == true){
			
			enviarInfo(""+vartipoproductos);
			
			txt1.setText(producto[1]);
			txt2.setText(producto[2]);
			txt3.setText(producto[3]);
			txt4.setText(producto[4]);
			txtp1.setText(precio[1]);
			txtp2.setText(precio[2]);
			txtp3.setText(precio[3]);
			txtp4.setText(precio[4]);
			
			Drawable image = ImageOperations(getApplicationContext(),"","image.jpg", url+imagen[1]);
            improd1.setImageDrawable(image);
            
			Drawable image2 = ImageOperations(getApplicationContext(),"","image2.jpg", url+imagen[2]);
            improd2.setImageDrawable(image2);
            
			Drawable image3 = ImageOperations(getApplicationContext(),"","image3.jpg", url+imagen[3]);
            improd3.setImageDrawable(image3);
            
			Drawable image4 = ImageOperations(getApplicationContext(),"","image4.jpg", url+imagen[4]);
            improd4.setImageDrawable(image4);


            improd1.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					agregarProducto(1);
				}
			});
            improd2.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					agregarProducto(2);

				}
			});
            improd3.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					agregarProducto(3);

				}
			});
            improd4.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					agregarProducto(4);

				}
			});
            

			
			

		}else if(internet == false){

            AlertDialog alertdialog=new AlertDialog.Builder(DetalleProductos.this).create();
			alertdialog.setIcon(R.drawable.ic_launcher);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
		
		
		
		
	}
	
	
	
	
	 protected void agregarProducto(int indice) {
		  ind=indice;
		 	AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("¿Desea agregar el artículo a su lista?")
			       .setCancelable(false)
			       .setPositiveButton("Sí", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   insert(ind);
			        	   dialog.cancel();
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   // put your code here 
			        	   dialog.cancel();
			           }
			       });
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		 
	}

	protected void enviarInfo(String vartipo) {
         String url="http://maskota.zedtrix.com/?sec=api&accion="+vartipo;
         Log.i("url mia", ""+url);
                 
                 URI myURI = null;
                 try {
                         myURI = new URI(url);
                 } catch (URISyntaxException e) {
                 }
                 HttpClient httpClient = new DefaultHttpClient();
                 HttpGet getMethod = new HttpGet(myURI);
                 HttpResponse webServerResponse = null;
                 try {
                         webServerResponse = httpClient.execute(getMethod);
                 }  catch (IOException e) {
                 }
                 
                 HttpEntity httpEntity = webServerResponse.getEntity();
        
                 //MANEJO DE LA RESPUESTA DEL SERVIDOR
                 
                 if (httpEntity != null) {
         
                         try {
                                 is = httpEntity.getContent();
                                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                     StringBuilder sb = new StringBuilder();
                     String line = null;
                     while ((line = reader.readLine()) != null) {
                             sb.append(line + "\n");
                     }
                     is.close();
                     result=sb.toString();
                     Log.i("Resultado", ""+result);
                     String array[]=result.split("@@@");
                     
                     producto = new String[array.length];
                     precio = new String[array.length];
                     imagen = new String[array.length];
                     id = new String[array.length];


                     for(int i =1;i<array.length;i++){
                    	String array2[] = array[i].split("%%%");
                    	producto[i]=array2[1];
                    	precio[i]=array2[2];
                    	imagen[i]=array2[3];
                    	id[i]=array2[0];

                      Log.i("size", ""+array2.length)	;

                     }
                     
                     for(int i=1; i<array.length; i++){
                         Log.i("Id", ""+id[i]);
                         }
                   for(int i=1; i<array.length; i++){
                   Log.i("Productos", ""+producto[i]);
                   }
                   for(int i=1; i<array.length; i++){
                   Log.i("Precio", ""+precio[i]);
                   }
                   for(int i=1; i<array.length; i++){
                   Log.i("Imagen", ""+imagen[i]);
                   }
                     


                         } catch (IllegalStateException e) {
                                 e.printStackTrace();
                         } catch (IOException e) {
                         }
                 }
         }
	 
     	private Drawable ImageOperations(Context ctx, String url, String saveFilename, String myurl) {
	         try {
	                 InputStream is = (InputStream) this.fetch(myurl);
	                 Drawable d = Drawable.createFromStream(is, "src");
	                 return d;
	         } catch (MalformedURLException e) {
	                 e.printStackTrace();
	                 return null;
	         } catch (IOException e) {
	                 e.printStackTrace();
	                 return null;
	         }
	     }
	
	     public Object fetch(String address) throws MalformedURLException,IOException {
	         URL url = new URL(address);
	         Object content = url.getContent();
	         return content;
         }
	     
         private void insert(int indice) {

         db = usdbh.getWritableDatabase();
         if(db != null)
         {
        	 
        	   posicion=indice;
               String[] argse = new String[] {id[posicion]};
               valor=id[posicion];
               Cursor c = db.rawQuery(" SELECT * FROM Articulos WHERE item=?", argse);
                              if (c.moveToFirst()) {
                                      AlertDialog.Builder builder = new AlertDialog.Builder(this);
                                              builder.setMessage("Este producto ya esta agregado. ¿Desea eliminarlo de la lista?")
                                                     
                                                     .setPositiveButton("Sí", new DialogInterface.OnClickListener() {
                                                         public void onClick(DialogInterface dialog, int id) {
                                                             db = usdbh.getWritableDatabase();

                                                        	 db.execSQL("DELETE FROM Articulos WHERE item="+valor+"");
                                                        	 dialog.cancel();
                                                         }
                                                     }).setNegativeButton("No", new DialogInterface.OnClickListener() {
														
														@Override
														public void onClick(DialogInterface arg0, int arg1) {

														}
													});
                                              AlertDialog alertDialog = builder.create();
                                              alertDialog.show();


                              }else{
                            	  Toast.makeText(getApplicationContext(), "Agregado a lista de compras", Toast.LENGTH_SHORT).show();
                            	  Log.i("QUERY", "INSERT INTO Articulos (item, producto, precio, urlimagen) VALUES (" +Integer.parseInt(id[indice])+
                               		   ",'"+producto[indice]+"',"+precio[indice]+",'"+imagen[indice]+"' )");
                                            db.execSQL("INSERT INTO Articulos (item, producto, precio, urlimagen) VALUES (" +Integer.parseInt(id[indice])+
                                         		   ",'"+producto[indice]+"',"+precio[indice]+",'"+imagen[indice]+"' )");
                                            
                                           
                            	  
                              }

      db.close();
        	 

       
     
         }           
     }
	
	
}











